<template>
  <div class="roleManagement">
    <div class="roleManagement_treeBg">
      <MetaChoiceList
        ref="roleManagement_list"
        title="角色"
        title-btn="新建"
        :list-data="roleDataStr"
        @roloeItemChoose="roloeItemChoose"
        @topBtnClick="newRoleBtnClick"
        @editBtnClick="editBtnClick"
        :treeBtn="choiceListTreeBtn"
      />
    </div>
    <div class="roleManagement_infoBg">
      <div class="roleManagement_info">
        <div v-if="Object.keys(roleInfoItem).length > 0" class="roleM_rightArea">
          <div class="roleM_infoTitleBg">
            <div class="roleM_infoTitle">角色信息</div>
            <el-button v-if="!roleInfoItem.enabled" type="success" plain size="mini" style="float:right" @click="doUseStatusChange('open')">启用</el-button>
            <el-button v-else type="danger" plain size="mini" style="float:right" @click="doUseStatusChange('close')">停用</el-button>
          </div>
          <el-form
            ref="roleInfo"
            :model="roleInfoItem"
            label-width="120px"
            size="mini"
            label-position="left"
            class="roleM_info"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="角色名称" :span="8">
                  <el-col class="roleM_infoLabel">{{ roleInfoItem.nameZh }}</el-col>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" :span="8">
                  <el-col class="roleM_infoLabel">{{ !roleInfoItem.enabled ? '已停用' : '已启用' }}</el-col>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="roleM_infoTitleBg">
            <div class="roleM_infoTitle">菜单权限</div>
          </div>
          <!-- <div id="btnSave">
            <el-button id="saveB" type="primary" size="small" @click="btnSave">保存</el-button>
          </div>
          <div id="line" /> -->
          <el-row :gutter="10" style="width: 100%;float:left">
            <el-col :span="12" class="f-box">
              <div class="box-title">
                <div class="box-title-left">
                  <el-checkbox
                    v-model="isCheckAllTofeature"
                    class="btn-check-all"
                    @change="changeSelectAllNode"
                  />
                  <span>菜单权限</span>
                  <el-button id="saveB" class="saveBtn" size="small" @click="btnSave">保存</el-button>
                </div>
              </div>
              <div class="box-content">
                <el-tree
                  ref="treeRef"
                  v-loading="treeLoadingFlag"
                  element-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading"
                  element-loading-background="rgba(0, 0, 0, 0.8)"
                  :data="treeData"
                  :props="treePorps"
                  node-key="id"
                  show-checkbox
                  highlight-current
                  default-expand-all
                  :default-checked-keys="checkedKeysArr"
                  @check-change="nodeChoose"
                />
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <el-dialog
      v-if="roleNewDialogFlag"
      :title="roleNewData.id && roleNewData.id !== '' ? '编辑角色' : '新建角色'"
      :visible.sync="roleNewDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="roleNew_form" :model="roleNewData" label-width="110px" :rules="rules">
        <el-form-item label="角色名称" prop="nameZh">
          <el-input v-model="roleNewData.nameZh" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="角色描述">
          <el-input v-model="roleNewData.remark" placeholder="请输入角色描述"></el-input>
        </el-form-item> -->
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="newDialogClose()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="newDialogSubmit()"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import MetaChoiceList from '../components/MetaChoiceList'
import deepClone from '../utils/deepClone'
export default {
  name: 'roleManagement',
  components: {
    MetaChoiceList
  },
  data () {
    return {
      roleNewDialogFlag: false,
      isCheckAllTofeature: false,
      treeLoadingFlag: false,
      roleDataStr: '',
      roleData: [],
      roleNewData: {},
      roleInfoItem: {},
      rules: {
        nameZh: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 10, message: '长度少于10个字', trigger: 'blur' }
        ]
      },
      treePorps: {
        label: 'nameZh',
        children: 'children',
        disabled: 'disabled'
      },
      checkedKeysArr: [], // 默认选中数组
      treeData: [],
      choiceListTreeBtn: {
        ifEdit: true,
        ifDelete: false
      }
    }
  },
  created() {
    this.initRoleData()
    this.getTreeData()
  },
  methods: {
    initRoleData() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/role",
        method: "get",
        params: {}
      }).then(res => {
        if (res.data.code === 200) {
          this.roleData = []
          let currentDataItem = {}
          for(let i in res.data.result) {
            let item = res.data.result[i]
            item.nameEn = res.data.result[i].name
            item.name = !res.data.result[i].enabled ? res.data.result[i].nameZh + '[已停用]' : res.data.result[i].nameZh
            this.roleData.push(item)
            if(Object.keys(this.roleInfoItem).length > 0 && this.roleInfoItem.id === item.id){
              currentDataItem = item
            }
          }
          this.roleDataStr = JSON.stringify(this.roleData)
          if(Object.keys(currentDataItem).length > 0) {
            this.roleInfoItem = deepClone(currentDataItem)
          }else {
            this.roleInfoItem = {}
          }
          this.$nextTick(() => {
            this.$refs.roleManagement_list.setChoiceRole(this.roleInfoItem)
          })

        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    getTreeData() {
      this.treeLoadingFlag = true
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "menu/list",
        method: "get"
      }).then(res => {
        if (res.data.code === 200) {
          this.treeData = []
          for(let i in res.data.result) {
            let item = res.data.result[i]
            item.nameZh = res.data.result[i].nameZh + "（" + res.data.result[i].value + "）"
            this.treeData.push(item)
          }
          this.treeLoadingFlag = false
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    roloeItemChoose(item) {
      this.roleInfoItem = deepClone(item)
      let myTableData = deepClone(this.treeData)
      this.treeData = []
      this.checkedKeysArr = []
      // for(let i in this.roleInfoItem.menus) {
      //   let menuItem = this.roleInfoItem.menus[i]
      //   for(let j in menuItem.children){
      //     this.checkedKeysArr.push(menuItem.children[j].id)
      //   }
      // }
      this.checkedKeysArr = deepClone(this.roleInfoItem.ids)

      let menuLength = 0
      for(let i in myTableData) {
        menuLength += myTableData[i].children.length
      }
      if(this.checkedKeysArr.length >= menuLength) {
        this.isCheckAllTofeature = true
      }else {
        this.isCheckAllTofeature = false
      }
      this.treeData = deepClone(myTableData)

    },
    newRoleBtnClick() {
      this.roleNewData = {
        id: '',
        nameZh: '',
      }
      this.roleNewDialogFlag = true
    },
    editBtnClick(item) {
      this.roleNewData = {
        id: item.id,
        nameZh: item.nameZh,
        enabled: item.enabled
      }
      this.roleNewDialogFlag = true
    },
    // deleteBtnClick(item) {
    //   this.$confirm('角色一经删除，相关用户将自动解除角色绑定。', '确认删除此角色?', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     let params = {}
    //     params.id = item.id
    //     this.$fetch({
    //       url: process.env.PROGOO_GATE_WATER + "admin/file/delete",
    //       method: "post",
    //       data: params
    //     }).then(res => {
    //       if (res.data.code === 200) {
    //         this.initRoleData()
    //       }else {
    //         this.$notify.error({
    //           title: '错误',
    //           message: res.data.message
    //         });
    //       }
    //     })
    //   })
    // },
    newDialogSubmit() {
      this.$refs['roleNew_form'].validate((valid) => {
        if (valid) {
          let params = {}
          if(this.roleNewData.id === '') {
            params.nameZh = this.roleNewData.nameZh
          }else {
            params.id = this.roleNewData.id
            params.nameZh = this.roleNewData.nameZh
            params.enabled = this.roleNewData.enabled
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "admin/role/edit",
            method: "put",
            data: params
          }).then(res => {
            if (res.data.code === 200) {
              this.initRoleData()
              this.newDialogClose()
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        } else {
          return false;
        }
      });
    },
    newDialogClose() {
      this.roleNewData = {
        id: '',
        nameZh: '',
      }
      this.roleNewDialogFlag = false
    },
    nodeChoose(data, nodeStatus, sonNodeStatus) {
      // if (data.dataType === 'function' && data.children && data.children.length > 0) {
      if (data.children && data.children.length > 0) {
        if (nodeStatus || (!nodeStatus && sonNodeStatus)) {
          const sonList = data.children
          const treeChoose = this.$refs.treeRef.getCheckedKeys()
          let index = 0
          const sonOnChoose = []
          for (const i in sonList) {
            for (const j in treeChoose) {
              if (sonList[i].id === treeChoose[j]) {
                index++
                sonOnChoose.push(treeChoose[j])
                break
              }
            }
          }
          if (sonOnChoose.length === 1) {
            this.$refs.treeRef.setChecked(data.id, true)
          }
        }
      }
    },
    changeSelectAllNode(val) {
      if (val) {
        this.$refs.treeRef.setCheckedNodes(this.treeData)
      } else {
        this.$refs.treeRef.setCheckedNodes([])
      }
    },
    doUseStatusChange(status) {
      let params = {}
      params.id = this.roleInfoItem.id
      if(status === 'open') {
        params.enabled = true
      }else {
        params.enabled = false
      }
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/role/status",
        method: 'put',
        data: params
      }).then(res => {
        if (res.data.code === 200) {
          this.initRoleData()
          this.$notify({
            title: '成功',
            message: '保存成功！',
            type: 'success',
            duration: 1500
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    btnSave() {
      const params = {}
      const halfTreeArr = this.$refs.treeRef.getHalfCheckedKeys()
      const treeArr = this.$refs.treeRef.getCheckedKeys()
      params.menusIds = []
      for(let i in halfTreeArr) {
        params.menusIds.push(halfTreeArr[i])
      }
      for(let i in treeArr) {
        params.menusIds.push(treeArr[i])
      }
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/role/menu?rid=" + this.roleInfoItem.id,
        method: 'put',
        data: params
      }).then(res => {
        if (res.data.code === 200) {
          this.initRoleData()
          this.$notify({
            title: '成功',
            message: '保存成功！',
            type: 'success',
            duration: 1500
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.roleManagement{
  width: 100%;
  height: 100%;
  display: flex;
  flex-grow: 1;
  box-sizing: border-box;
  padding: 15px;
  .roleManagement_treeBg {
    height: 100%;
  }
  .roleManagement_infoBg {
    height: 100%;
    box-sizing: border-box;
    padding: 0 7px;
    flex: 1;
  }
  .roleManagement_info {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    border: 1px solid rgb(228, 234, 236);
    flex: 1;
    overflow-y: scroll;
    box-sizing: border-box;
    padding: 15px;
    .roleM_rightArea {
      .roleM_infoTitleBg {
        width: 100%;
        float: left;
        // margin-top: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
        .roleM_infoTitle {
          font-size: 20px;
          float: left;
          height: 30px;
          line-height: 30px;
        }
      }
      .roleM_info {
        width: 100%;
        float: left;
        padding-top: 10px;
        .roleM_infoLabel {
          color: #606266;
        }
      }
      #btnSave {
        margin: 10px 15px;
      }
      #line {
        float: clean;
        height: 1px;
        border-bottom: 1px solid #d5dbe2;
        margin: 8px 15px 20px;
      }
      .f-box {
        border-radius: 3px;
        border: 1px solid #d5dbe2;
        padding: 0 !important;
        height: 100%;
        margin-top: 15px;
        margin-left: 8px;
        .box-title {
          background-color: #f5f7f9;
          width: 100%;
          height: 10%;
          font-size: 16px;
          color: #4a4a4a;
          line-height: 40px;
          padding-left: 24px;
          display: flex;
          box-sizing: border-box;
          div {
            flex: 1;
          }
          .box-title-left {
            text-align: left;
            .btn-check-all {
              margin-right: 4px;
            }
            .saveBtn {
              float: right;
              margin-top: 5px;
              margin-right: 10px;
            }
          }
        }
        .box-content {
          width: 100%;
          height: 90%;
          border-top: 1px solid #d5dbe2;
          box-sizing: border-box;
          padding: 10px 0;
          .el-tree {
            max-height: 600px;
            overflow: auto;
          }
          .el-tree-node__content {
            .handles {
              opacity: 0;
              margin-right: 20px;
              position: absolute;
              right: 0;
              .handles-item {
                margin-left: 8px;
                &:hover {
                  color: #409eff;
                }
              }
            }
            &:hover {
              .handles {
                opacity: 1;
              }
            }
          }
          &::-webkit-scrollbar {
            width: 6px;
            height: 6px;
          }
          &::-webkit-scrollbar-track {
            background: #ffffff;
          }
          &::-webkit-scrollbar-thumb {
            background: hsla(220, 4%, 58%, 0.3);
            border-radius: 4px;
          }
        }
      }
    }
  }
}
.dialogFooter {
  display: flex;
  justify-content: center;
  margin-top: 0.5rem;
}
</style>
